package com.lg.concurrent.schedule;

import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 当守护线程持有需要关闭的资源，爹死了会怎样？
 *  无错，不会怎样
 *
 *  内存泄露：对象被其他长周期的线程引用，但有不用，导致无法被gc
 */
public class DaemonThread {
    @SneakyThrows
    public static void main(String[] args) {
        ThreadLocal<Object> objectThreadLocal = new ThreadLocal<>();
        DaemonT daemonT = new DaemonT();
        daemonT.setDaemon(true);
        daemonT.start();
        Thread.sleep(1000);
        System.out.println("main end");
    }
}


class  DaemonT extends Thread{
    @SneakyThrows
    @Override
    public void run() {
        ClassPathResource listRes = new ClassPathResource("data/dict");
        InputStream inputStream = null;
        BufferedReader br = null;
        try {
             inputStream = listRes.getInputStream();
             br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            String s = br.readLine();
            while (s != null){
                Thread.sleep(1000);
                System.out.println(s);
                s = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            br.close();
            inputStream.close();
        }
    }
}
